﻿/// <reference path="zepto.min.js" />
/// <reference path="config.js" />
/// <reference path="common.js" />

jc.rem.on();

function clearCookie() {
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
        for (var i = keys.length; i--;)
            document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
    }
}

if (jc.cookie.get("user")) {
    clearCookie();
}

jc.uiExtend("header", {
    //user: JSON.parse(localStorage.getItem("user") || null),
    hideReturn: function () {
        this.$element.addClass("hideReturn");
    },
    user: (function () {
        var result = null;

        var accessToken = jc.cookie.get("accessToken");
        var uid = jc.cookie.get("uid");
        var avatar = jc.cookie.get("avatar");
        var username = jc.cookie.get("username");

        if (accessToken && uid) {
            result = {}
            result.accessToken = accessToken;
            result.uid = uid;
            result.username = username;
            result.avatar = avatar == "null" ? null : avatar + "?imageMogr/auto-orient";
        }

        return result;

    })(),
    site: (function () {
        var result = {};

        var logoUrl = jc.cookie.get("logoUrl");
        var siteKeyword = jc.cookie.get("siteKeyword");
        var siteTitle = jc.cookie.get("siteTitle");

        result.logoUrl = logoUrl;
        result.siteKeyword = siteKeyword;
        result.siteTitle = siteTitle == "null" ? null : siteTitle;

        document.title = result.siteTitle;

        return result;

    })(),
    title: "",
    logo: "",
    returnUrl: "",
    navCurrent: -1,
    navData: [
        {
            title: "首页",
            url: window.ctx + "index/index.html",
        },
        {
            title: "课程",
            url: window.ctx + "courseList/courseList.html",
        }
    ],
    getUser: function (fn, disableErrorRouter) {
        if (!this.user && !disableErrorRouter) {
            window.errorRouter("login");
        }
        if (fn) fn(this.user);
    },
    getSite: function (fn) {
        if (fn) fn(this.site);
    },
    updateLogo: function (url) {
        this.logo = url || "";
        this.setup();
    },
    updateTitle: function (str) {
        this.title = str || "";
        this.setup();
    },
    updateReturnUrl: function (url) {
        this.returnUrl = url || "javascript:;";
        this.setup();
    },
    updateNavCurrent: function (eq) {
        this.navCurrent = eq;
        this.setup();
    },
    setup: function (data) {
        this.$inner.html(this.template(data || this.user));
    },
    logout: function () {
        //localStorage.removeItem("user");
        this.getUser(function (user) {
            if (user) {
                for (var attr in user) {
                    jc.cookie.remove(attr);
                }
            }
        });
        window.location.href = window.ctx + "index/index.html";
    },
    template: function (opt) {
        var html = '';

        var opt = opt || {};



        html += '<div class="i_logo">';
        html += '<a href="' + window.ctx + "index/index.html" + '">';
        html += '<img src="' + this.site.logoUrl + '">';
        html += '</a>';
        html += '</div>';

        html += '<div class="i_return">';
        html += '<a href="javascript:window.history.back();"><i class="icon">&#xe408;</i></a>';
        html += '</div>';

        html += '<div class="i_nav clearfix">';

        for (var i = 0, l = this.navData.length; i < l; i++) {
            var cur = this.navData[i];
            html += '<div class="n_item' + (i == this.navCurrent ? ' current' : '') + '"><a href="' + cur.url + '"><i></i><span>' + cur.title + '</span></a></div>';
        }

        html += '</div>';
        html += '<div class="i_title">';
        html += '<div class="c_txt">' + this.title + '</div>';
        html += '</div>';


        if (this.user) {
            html += '<div class="i_userInfo">';

            html += '<div class="u_default">';
            html += '<a href="javascript:;">';
            html += '<img src="' + (opt.avatar || "../images/default_face.png") + '">';
            html += '</a>';
            html += '</div>';

            html += '<div class="u_menu">';
            html += '<div class="m_item"><a href="' + (window.ctx + "index/index.html") + '">首页推荐</a></div>';
            html += '<div class="m_item"><a href="' + (window.ctx + "courseList/courseList.html") + '">选课中心</a></div>';
            html += '<div class="m_item"><a href="' + (window.ctx + "home/home.html") + '">个人中心</a></div>';
            html += '<div class="m_item"><a onclick="jc.ui.header.trigger(\'logout\');" href="javascript:;">退出登录</a></div>';
            html += '</div>';

            html += '</div>';
        }
        else {
            html += '<div class="i_login">';
            html += '<a href="javascript:(window.errorRouter(\'login\'));">';
            html += '登录';
            html += '</a>';
            html += '</div>';
        }



        return html;
    },
    init: function () {

        var _this = this;

        this.$inner = this.$element.find(".h_inner");


        this.$element.click(function (e) {
            var e = e || window.event;
            if (e.stopPropagation) { //如果提供了事件对象，则这是一个非IE浏览器 
                e.stopPropagation();
            } else {
                //兼容IE的方式来取消事件冒泡 
                window.event.cancelBubble = true;
            }
        });

        $(document.documentElement).click(function () {
            _this.$element.removeClass("openMenu");
        });

        /* 点击头像 */
        this.$element.on("click", ".u_default", function (e) {
            if (_this.user) {
                /* 已登录 */
                _this.$element.toggleClass("openMenu");
            }
            else {
                /* 未登录 */

                window.location.href = window.ctx + "login/login.html";

            }

        });
    }

});

jc.uiExtend("courseHolder", {
    router: "",
    keyword: [],
    hasKeyword: function (keyword) {
        for (var i = 0, l = this.keyword.length; i < l; i++) {
            if (keyword == this.keyword[i]) {
                return true;
            }
        }
        return false;
    },
    mergeDataArrayAttribute: function (data, data2, key, fn) {

        for (var i = 0, l = data.length; i < l; i++) {
            var dataKey = data[i][key];

            for (var j = 0, len = data2.length; j < len; j++) {
                var data2Key = data2[j][key];
                if (dataKey == data2Key) {
                    for (var attr in data2[j]) {
                        data[i][attr] = data2[j][attr];
                    }
                }
            }
        }

        if (fn) fn(data);

    },
    getDataArrayAttribute: function (data, key, fn) {
        var result = [];

        if (data.length) {
            for (var i = 0, l = data.length; i < l; i++) {
                result[i] = data[i][key];
            }
        }

        if (fn) fn(result.join("|"));
    },
    formatNumberLength: function (number) {
        var number = number.toString();
        if (number.length < 2) {
            return '0' + number;
        }
        return number;
    },
    formatTimestamp: function (timestamp) {
        var result = "";

        var date = new Date();

        date.setTime(timestamp);

        var stringYear = date.getFullYear() + '-';
        var staringMonth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var stringDate = this.formatNumberLength(date.getDate()) + ' ';
        var stringHours = this.formatNumberLength(date.getHours()) + ':';
        var stringMinutes = this.formatNumberLength(date.getMinutes());

        result = stringYear + staringMonth + stringDate + stringHours + stringMinutes;

        return result;

    },
    template: function (opt) {
        var html = '';

        /* 是否在直播 */
        var isLiving = opt.livingStatus == 1;

        //console.log(opt.title, isLiving);
        //console.log(opt);
        html += '<div data-courseId="' + opt.courseId + '" data-is-living="' + isLiving + '" data-lectureId="' + opt.livingLectureId + '" data-shopping-cart-id="' + (opt.shoppingCartId || "") + '" class="i_item' + (opt.initClass ? " " + opt.initClass : "") + '">';

        html += '<div class="i_left">';
        html += '<div class="l_token">';

        if (this.hasKeyword("token")) {

            /* 没购买 */
            if (!opt.sign) {
                html += '<i class="i1"></i>';
            }

        }

        html += '</div>';
        html += '<div class="l_picture">';
        html += '<img src="' + opt.cover + '" />';
        html += '</div>';
        html += '</div>';
        html += '<div class="i_right">';

        if (this.hasKeyword("title")) {
            /* 标题 */
            html += '<div class="r_title">';
            html += opt.title;
            html += '</div>';
        }

        if (this.hasKeyword("price")) {
            if (opt.sign) {
                /* 已购买 */
                /* 价钱 */
                html += '<div class="r_sign">';
                html += "已购买";
                html += '</div>';
            } else {
                /* 价钱 */
                html += '<div class="r_price">';
                html += "￥" + opt.price;
                html += '</div>';
            }

        }

        if (this.hasKeyword("label")) {
            /* 科目年级 */
            html += '<div class="r_label">';
            html += '<div class="l_item">';
            html += opt.subjectName;
            html += '</div>';
            html += '<div class="l_item">';
            html += opt.gradeName;
            html += '</div>';
            html += '</div>';
        }

        if (this.hasKeyword("realtimeOnlineCount")) {
            /* 在线观看人数 */
            html += '<div class="r_realtimeOnlineCount">';
            html += (opt.realtimeOnlineCount || 0) + "人正在观看";
            html += '</div>';
        }

        if (this.hasKeyword("lectureCount")) {
            /* 讲数 */
            html += '<div class="r_lectureCount">';
            html += opt.lectureCount + "讲";
            html += '</div>';
        }

        if (this.hasKeyword("signAmount")) {
            /* 多少人报名 */
            html += '<div class="r_signAmount">';
            html += opt.signAmount + "人报名";
            html += '</div>';
        }

        if (this.hasKeyword("courseProgress")) {
            /* 开课时间 */
            html += '<div class="r_courseProgress">';

            //1|2|startTime|endTime|title|lectureId
            if (isLiving) {
                /* 显示正在直播 */
                html += '<div class="r_living">';
                html += '<a href="../player/living.html"><span>正在直播</span><i></i></a>';
                html += '</div>';
            }
            else {
                /* 显示时间 */
                html += '<div class="c_startTime">';
                html += '开课:' + this.formatTimestamp(opt.startTime);
                html += '</div>';
            }

            html += '</div>';
        }


        html += '</div>';
        html += '</div>';

        return html;

    },
    append: function (data) {
        var html = '';
        for (var i = 0, l = data.length; i < l; i++) {
            html += this.template(data[i]);
        }
        this.$inner.append(html);

        this.courseHolderItemChange();
    },
    setup: function (data) {
        if (!data.length) {
            var $parent = this.$element.parents("[data-source-parent='" + this.source + "']");
            if ($parent.length) {
                $parent.hide();
            }
            else {
                this.$inner.html('<div class="i_null">' + (this.nullTips ? this.nullTips : "Sorry！暂无课程数据!") + '</div>');
            }
        }
        else {
            var html = '';
            for (var i = 0, l = data.length; i < l; i++) {
                html += this.template(data[i]);
            }

            this.$inner.html(html);
        }

        this.courseHolderItemChange();
    },
    courseHolderItemRemove: function (array) {
        if (!array.length) return;

        var $item = this.$inner.children();

        var flag = confirm("是否删除" + array.length + "课程?");

        if (!flag) return;

        for (var i = 0, l = array.length; i < l; i++) {
            $item.eq(array[i]).removeClass("checked");
            $item.eq(array[i]).addClass("remove");
        }

        if (window.courseHolderItemRemove) window.courseHolderItemRemove($item.filter(".remove"));

        this.courseHolderItemChange();

    },
    courseHolderItemChange: function () {

        if (this.source != "shoppingCart") return false;

        var $item = this.$inner.children();

        var $item_checked = $item.filter(".checked").not(".remove");

        if ($item_checked.length >= 1) {
            this.$controller.show();
            if (jc.hasUI("cartListFooter")) {
                jc.ui.cartListFooter.trigger("show");
            }
        }
        else {
            this.$controller.hide();
            if (jc.hasUI("cartListFooter")) {
                jc.ui.cartListFooter.trigger("hide");
            }
        }

        if (!$item.not(".remove").length) {
            this.$inner.html('<div class="i_null">' + (this.nullTips ? this.nullTips : "Sorry！暂无课程数据!") + '</div>');
        }


        if ($item.not(".remove").length == $item_checked.length) {
            this.$controller_selectAll.addClass("checked");
        }
        else {
            this.$controller_selectAll.removeClass("checked");
        }

        this.$controller_selectAll_count.html($item_checked.length);


        if (window.courseHolderItemChange) window.courseHolderItemChange($item);
    },
    init: function () {
        var _this = this;

        this.nullTips = this.$element.attr("data-null-tips");
        this.source = this.$element.attr("data-source");
        this.router = this.$element.attr("data-router");
        this.clickToggleClass = this.$element.attr("data-click-toggle-class");
        this.keyword = (this.$element.attr("data-keyword") || "").split(",");

        this.$inner = this.$element.find(".c_inner");

        this.$controller = this.$element.find(".c_controller");
        this.$controller_selectAll = this.$controller.find(".l_selectAll");
        this.$controller_selectAll_count = this.$controller_selectAll.find("span");
        this.$controller_btn = this.$controller.find(".r_btn");



        this.$inner.on("click", ".i_item", function () {
            var courseId = $(this).attr("data-courseId");
            var lectureId = $(this).attr("data-lectureId");

            /* 如果有地址就链接到地址 */
            if (_this.router) {
                var hash = [];

                if (_this.router == "player/living.html") {
                    hash.push("lectureId=" + lectureId);
                }
                else if (_this.router == "courseDetails/courseDetails.html") {
                    hash.push("courseId=" + courseId);
                }
                else if (_this.router == "home/courseDetails.html") {
                    hash.push("courseId=" + courseId);
                }

                window.location.href = window.ctx + _this.router + "#" + hash.join(";");
            }

            /* 如果有点击真假 */
            if (_this.clickToggleClass) {
                $(this).toggleClass(_this.clickToggleClass);

                _this.courseHolderItemChange();
            }

        });

        this.$controller_selectAll.click(function () {
            var $this = $(this);
            var $item = _this.$inner.children(".i_item");

            if ($this.hasClass("checked")) {
                $item.removeClass("checked");
            }
            else {
                $item.not(".remove").addClass("checked");
            }

            _this.courseHolderItemChange();

        });



        this.$controller_btn.on("click", "a", function () {
            var $item = _this.$inner.children(".i_item");
            var $item_checked = $item.filter(".checked");
            var array = [];

            $item_checked.each(function (i, obj) {
                array.push($(obj).index());
            });

            _this.courseHolderItemRemove(array);
        });



    }
});

jc.uiExtend("nav", {
    eq: function (eq) {

    },
    template: function (index, name, jumpUrl, imgUrl) {
        var html = "";

        html += '<div class="c_item i' + (index + 1) + '">';
        html += '<a href="' + jumpUrl + '">';
        html += '<i></i>';
        html += '<span>' + name + '</span>';
        html += '</a>';
        html += '</div>';

        return html;

    },
    setup: function (data) {
        var _this = this;

        var html = ""

        $.each(window.nav.data, function (i, obj) {
            html += _this.template(i, obj.name, obj.jumpUrl, obj.imgUrl);
        });
        this.$center.html(html);

        this.$center_item = this.$center.children();

        this.$center_item.eq(window.nav.current).addClass("current");

        this.setWidth();

    },
    setWidth: function () {
        this.$center_item.width(100 / this.$center_item.length + "%");
    },
    init: function () {
        this.$center = this.$element.find(".i_center");
        this.$center_item = null;

        this.setup();
    }
});

jc.uiExtend("banner", {
    template: function (opt) {
        var html = "";
        html += '<div class="swipe-wrap">';

        for (var i = 0, l = opt.length; i < l; i++) {
            html += '<div>';
            html += '<a href="' + opt[i].clickUrl + '">';
            html += '<img src="' + opt[i].pictureUrl + '" />';
            html += '</a>';
            html += '</div>';
        }
        html += '</div>';
        html += '<div id="swipe-count" class="swipe-count">';

        for (var i = 0, l = opt.length; i < l; i++) {
            html += '<a class="' + (i == 0 ? 'active' : '') + '" href="javascript:;"></a>';
        }

        html += '</div>';

        return html;
    },
    setup: function (data) {
        var _this = this;

        if (!data.length) {
            this.$element.hide();
            return;
        }

        this.$element.html(this.template(data));

        window.mySwipe = new Swipe(this._element, {
            startSlide: 0,
            speed: 400,
            auto: 2000,
            continuous: true,
            disableScroll: false,
            stopPropagation: false,
            callback: function (index, elem) {
                var count = _this.$element.find(".swipe-count a");
                count.eq(index).addClass("active").siblings().removeClass("active");

            },
            transitionEnd: function (index, elem) { }
        });

    },
    init: function () {
        var _this = this;

        this.$div = this.$element.find(".swipe-wrap").children();
        this.$count = this.$element.find(".swipe-count");

    }

});

jc.uiExtend("orderHolder", {
    router: "",
    keyword: [],
    hasKeyword: function (keyword) {
        for (var i = 0, l = this.keyword.length; i < l; i++) {
            if (keyword == this.keyword[i]) {
                return true;
            }
        }
        return false;
    },
    formatNumberLength: function (number) {
        var number = number.toString();
        if (number.length < 2) {
            return '0' + number;
        }
        return number;
    },
    formatTimestamp: function (timestamp) {
        var result = "";

        var date = new Date();

        date.setTime(timestamp);

        var stringYear = date.getFullYear() + '.';
        var staringMonth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
        var stringDate = this.formatNumberLength(date.getDate()) + ' ';
        var stringHours = this.formatNumberLength(date.getHours()) + ':';
        var stringMinutes = this.formatNumberLength(date.getMinutes());

        result = stringYear + staringMonth + stringDate + stringHours + stringMinutes;

        return result;

    },
    template: function (opt) {
        var html = '';

        html += '<div class="o_item" data-order-id="' + opt.orderId + '">';
        html += '<div class="i_header clearfix">';
        html += '<div class="h_left">';
        html += '<div class="l_orderId">订单编号：' + opt.orderId + '</div>';
        html += '</div>';
        html += '<div class="h_right">';
        html += '<div class="r_status">';

        var status = "";

        // 0关闭 1为支付 2已支付 空全部

        if (opt.status == 0) {
            status = "已取消"
        }
        else if (opt.status == 1) {
            status = "未支付"
        }
        else if (opt.status == 2) {
            status = "已支付"
        }


        html += '<span>' + status + '</span>';

        if (opt.status == 1) {
            html += '<a data-type="del" class="abtn link cDefault" href="javascript:;">取消</a>';
        }
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '<div class="i_main">';

        for (var i = 0, l = opt.tradeMirror.length; i < l; i++) {
            html += this.templateListItem(opt.tradeMirror[i]);
        }

        html += '</div>';
        html += '<div class="i_details">';
        html += '<div class="d_column clearfix">';
        html += '<div class="c_left">';

        html += '<div class="l_txt">合计金额： ￥' + opt.payMoney + '</div>';
        html += '</div>';
        html += '<div class="c_right">';
        html += '<div class="r_txt">已优惠：￥' + (parseFloat(opt.totalMoney) - parseFloat(opt.payMoney)) + '</div>';
        html += '</div>';
        html += '</div>';

        if (opt.status == 1) {

            html += '<div class="d_btn">';
            html += '<a data-type="pay" class="abtn orange" href="javascript:;">马上支付</a>';
            html += '</div>';

        }



        html += '</div>';
        html += '</div>';


        return html;
    },
    templateListItem: function (opt) {
        var html = '';

        /* 是否在直播 */
        var isLiving = opt.livingStatus == 1;

        //console.log(opt.title, isLiving);

        html += '<div data-courseId="' + opt.courseId + '" data-is-living="' + isLiving + '" data-shopping-cart-id="' + (opt.shoppingCartId || "") + '" class="m_item' + (opt.initClass ? " " + opt.initClass : "") + '">';

        html += '<div class="i_left">';
        html += '<div class="l_token">';
        html += '<i class="i1"></i>';
        html += '</div>';
        html += '<div class="l_picture">';
        html += '<img src="' + opt.cover + '" />';
        html += '</div>';
        html += '</div>';
        html += '<div class="i_right">';

        if (this.hasKeyword("title")) {
            /* 标题 */
            html += '<div class="r_title">';
            html += opt.title;
            html += '</div>';
        }

        if (this.hasKeyword("price")) {
            /* 价钱 */
            html += '<div class="r_price">';
            html += "￥" + opt.price;
            html += '</div>';
        }

        if (this.hasKeyword("label")) {
            /* 科目年级 */
            html += '<div class="r_label">';
            html += '<div class="l_item">';
            html += opt.subjectName;
            html += '</div>';
            html += '<div class="l_item">';
            html += opt.gradeName;
            html += '</div>';
            html += '</div>';
        }

        if (this.hasKeyword("realtimeOnlineCount")) {
            /* 在线观看人数 */
            html += '<div class="r_realtimeOnlineCount">';
            html += opt.realtimeOnlineCount + "人正在观看";
            html += '</div>';
        }

        if (this.hasKeyword("lectureCount")) {
            /* 多少人观看 */
            html += '<div class="r_lectureCount">';
            html += opt.lectureCount + "人报名";
            html += '</div>';
        }

        if (this.hasKeyword("courseProgress")) {
            /* 开课时间 */
            html += '<div class="r_courseProgress">';

            //1|2|startTime|endTime|title|lectureId
            if (isLiving) {
                /* 显示正在直播 */
                html += '<div class="r_living">';
                html += '<a href="../player/living.html"><span>正在直播</span><i></i></a>';
                html += '</div>';
            }
            else {
                /* 显示时间 */
                html += '<div class="c_startTime">';
                html += '开课:' + this.formatTimestamp(opt.startTime);
                html += '</div>';
            }

            html += '</div>';
        }


        html += '</div>';
        html += '</div>';

        return html;

    },
    chekMainNull: function () {
        var length = this.$element.children().length;
        if (!length) {
            this.$element.html('<div class="o_null">暂无课程数据!</div>');
        }
    },
    append: function (data) {
        var html = '';
        for (var i = 0, l = data.length; i < l; i++) {
            html += this.template(data[i]);
        }
        this.$element.append(html);
        this.chekMainNull();
    },
    setup: function (data) {
        var html = '';
        for (var i = 0, l = data.length; i < l; i++) {
            html += this.template(data[i]);
        }
        this.$element.html(html);
        this.chekMainNull();
    },
    changeStatus: function ($item, status) {

        if (status == 0) {
            $item.addClass("remove");
            var $item_status = $item.find(".i_header .h_right .r_status span");

            $item_status.html("已取消");
        }

    },
    init: function () {
        var _this = this;

        this.router = this.$element.attr("data-router");
        this.keyword = (this.$element.attr("data-keyword") || "").split(",");

        this.$element.on("click", "a", function () {
            var $this = $(this);
            var type = $(this).attr("data-type");
            if (type == "del") {

                var flag = confirm("您是否取消此订单?");

                if (flag) {

                    jc.ui.header.trigger("getUser", function (user) {
                        var $item = $this.parents(".o_item");
                        var orderId = $item.attr("data-order-id");

                        $.getJSON(window.path.closeOrder, {
                            accessToken: user.accessToken,
                            userId: user.uid,
                            orderId: orderId
                        }, function (result) {
                            if (result.success) {
                                _this.changeStatus($item, 0);
                            }
                            else {
                                window.errorRouter(result.desc);
                            }
                        });

                    });


                }
            }

            if (type == "pay") {

                jc.loading.show();

                jc.ui.header.trigger("getUser", function (user) {
                    var $item = $this.parents(".o_item");
                    var orderId = $item.attr("data-order-id");

                    $.getJSON(window.path.payOrder, {
                        accessToken: user.accessToken,
                        userId: user.uid,
                        orderId: orderId
                    }, function (result) {
                        if (result.success) {

                            jc.loading.hide();

                            var data = result.data;

                            var payUrl = data.payUrl;

                            if (payUrl == "") {
                                /* 0元购买 去个人中心 */
                                window.location.href = window.ctx + "home/courseList.html";
                            }
                            else {
                                if (window.isWeixn()) {
                                    payUrl = payUrl.replace("page_type=1", "page_type=3");
                                }
                                else {
                                    payUrl = payUrl.replace("page_type=1", "page_type=2");
                                }
                                window.location.href = payUrl;
                            }

                            //window.location.href = payUrl;
                        }
                        else {
                            window.errorRouter(result.desc);
                        }
                    });

                });

                // payOrder

            }

        });

        this.$element.on("click", ".l_item", function () {
            var courseId = $(this).attr("data-courseId");

            /* 如果有地址就链接到地址 */
            if (_this.router) {
                var hash = [];
                hash.push("courseId=" + courseId);

                window.location.href = window.ctx + _this.router + "#" + hash.join(";");
            }
        });

    }

});

jc.uiExtend("filterTab", {
    setup: function (array) {

        var html = "";

        for (var i = 0, l = array.length; i < l; i++) {
            var cur = array[i];

            html += '<div data-value="' + cur.value + '" class="i_item">';
            html += '<div class="i_default"><a href="javascript:;"><span>' + cur.key + '</span><i class="icon">&#xe5c5;</i></a></div>';
            html += '<div class="i_menu">';

            for (var j = 0, len = cur.children.length; j < len; j++) {
                html += '<div data-value="' + (cur.children[j].value || "") + '" class="m_item' + (j == 0 ? " current" : "") + '"><a href="javascript:;">' + array[i].children[j].key + '</a></div>';
            }

            html += '</div>';
            html += '</div>';
        }
        this.$inner.html(html);

        this.$inner_select = this.$inner.find("select");
        this.$inner_item = this.$inner.children();


        if (this.itemWidth == "full") {
            this.setWidth();
        }

    },
    setWidth: function () {
        this.$inner_item.width(100 / this.$inner_item.length + "%");
    },

    close: function () {
        var data = {};
        var _this = this;

        setTimeout(function () {

            $(_this.$inner_item).each(function (i, obj) {
                var $obj = $(obj);

                var $current = $obj.find(".m_item.current");
                if ($current.length) {
                    data[$obj.attr("data-value")] = $current.attr("data-value");
                }
            });

            if (window.filterTabChange) window.filterTabChange(data);

            _this.$element.removeClass("active");
            _this.$inner_item.removeClass("current");


        }, 1);

    },
    init: function () {
        var _this = this;

        this.itemWidth = this.$element.attr("data-item-width");
        this.type = this.$element.attr("data-type");

        this.$inner = this.$element.find(".f_inner");
        this.$inner_item = null;
        this.$inner_select = null;

        this.$mask = this.$element.find(".f_mask");

        this.$mask.click(function () {
            _this.close();
        });

        this.$element.on("click", ".i_item", function () {
            var $this = $(this);
            _this.$element.addClass("active");
            if ($this.hasClass("current")) {
                $this.removeClass("current");
            }
            else {
                $this.addClass("current").siblings().removeClass("current");
            }
        });

        this.$element.on("click", ".i_menu .m_item", function () {
            var $this = $(this);
            var $default = $this.parents(".i_menu").prev(".i_default").find("span");
            var $a = $this.find("a");

            $this.addClass("current").siblings().removeClass("current");

            $default.html($a.html());


            _this.close();
        });


    }
});

jc.uiExtend("courseDetails", {
    formatNumberLength: function (number) {
        var number = number.toString();
        if (number.length < 2) {
            return '0' + number;
        }
        return number;
    },
    formatTimestamp: function (timestamp) {
        var result = "";

        var date = new Date();

        date.setTime(timestamp);

        var stringYear = date.getFullYear() + '.';
        var staringMonth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
        var stringDate = this.formatNumberLength(date.getDate()) + ' ';
        var stringHours = this.formatNumberLength(date.getHours()) + ':';
        var stringMinutes = this.formatNumberLength(date.getMinutes());

        result = stringYear + staringMonth + stringDate;

        return result;

    },
    template: function (opt) {
        var html = '';

        html += '<div class="c_picture">';
        html += '<img src="' + opt.cover + '" />';
        html += '</div>';
        html += '<div class="c_details">';
        html += '<div class="d_column">';
        html += '<div class="c_left">';
        html += '<div class="l_title">';
        html += opt.title;
        html += '</div>';
        html += '</div>';
        html += '<div class="c_right">';
        html += '<div class="r_price">￥' + opt.price + '</div>';
        html += '</div>';
        html += '</div>';
        html += '<div class="d_txt">主讲老师：<span>' + opt.teacherName + '</span></div>';
        html += '<div class="d_txt">';
        html += '上课时间：<span>' + this.formatTimestamp(opt.startTime) + ' - ' + this.formatTimestamp(opt.endTime) + '</span>';

        if (opt.livingStatus == 1) {
            html += '<a class="abtn green" href="' + window.ctx + "player/living.html#lectureId=" + opt.livingLectureId + '">' + this.btnTxt + '</a>';
        }

        html += '</div>';
        html += '</div>';


        return html;
    },
    setup: function (data) {
        this.$element.html(this.template(data));
    },
    init: function () {
        this.btnTxt = this.$element.attr("data-btn-txt");

    }

});

jc.uiExtend("defaultTab", {
    jump: function (eq) {
        this.$title_item.eq(eq).addClass("current").siblings().removeClass("current");
        this.$main_item.eq(eq).addClass("current").siblings().removeClass("current");
    },
    setWidth: function () {
        this.$title_item.width(100 / this.$title_item.length + "%");
    },
    init: function () {
        var _this = this;

        this.$title_item = this.$element.find(".i_item");
        this.$main_item = this.$element.find(".m_item");


        this.$title_item.click(function () {
            _this.jump($(this).index());
        });


        if (this.$element.attr("data-item-width") == "auto") {
            this.setWidth();
        }


    }

});

jc.uiExtend("courseDetailsEditOutPut", {
    setup: function (data) {
        this.$element.html(data);
    },
    init: function () {

    }

});

jc.uiExtend("cart", {
    timer: null,
    add: function (courseId, fnSuccess) {

        var _this = this;

        jc.ui.header.trigger("getUser", function (user) {

            $.getJSON(window.path.cartAdd, { accessToken: user.accessToken, userId: user.uid, courseId: courseId }, function (result) {
                if (result.success) {
                    _this.update();
                    if (fnSuccess) fnSuccess(result.data.shoppingCartId);
                }
                else {
                    window.errorRouter(result.desc);
                }
            });
        });

    },
    update: function () {

        var _this = this;

        jc.ui.header.trigger("getUser", function (user) {
            $.getJSON(window.path.cartCount, { accessToken: user.accessToken, userId: user.uid }, function (result) {
                var data = result.data;
                if (result.success) {
                    _this.$count.html(data.count);
                    clearInterval(_this.timer);
                    _this.timer = setInterval(function () {
                        _this.update();
                    }, 1000);
                }
                else {
                    //window.errorRouter(result.desc);
                }
            });
        }, true);
    },
    init: function () {
        var _this = this;

        this.$count = this.$element.find(".i_count");
        this.$link = this.$element.find(".i_link a");

        jc.ui.header.trigger("getUser", function (user) {
            if (user) {
                _this.$link.attr("href", window.ctx + "cartList/cartList.html");
                _this.update();
                _this.$element.show();
            }
        }, true);



    }

});

jc.uiExtend("courseDetailsFooter", {
    user: JSON.parse(localStorage.getItem("user") || null),
    init: function () {
        var _this = this;

        var courseId = jc.hash.get("courseId");

        this.$element.on("click", ".i_item a", function () {

            var type = $(this).attr("data-type");

            if (type == "add") {
                jc.ui.cart.trigger("add", courseId);
            }
            else if (type == "pay") {
                jc.ui.cart.trigger("add", courseId, function (shoppingCartId) {
                    window.location.href = window.ctx + "orderConfirm/orderConfirm.html#shoppingCartIds=" + shoppingCartId;
                });
            }

        });

    }
});

jc.uiExtend("cartListFooter", {
    shoppingCartIds: [],
    show: function () {
        this.$element.show();
    },
    hide: function () {
        this.$element.hide();
    },
    template: function (opt) {
        var html = '';

        this.shoppingCartIds = opt.shoppingCartIds;

        html += '<div class="i_left">';
        html += '<div class="l_discount">';
        html += '已优惠：￥' + opt.discountPrice;
        html += '</div>';
        html += '<div class="l_price">';
        html += '共需支付：￥' + opt.payPrice;
        html += '</div>';
        html += '</div>';
        html += '<div class="i_right">';
        html += '<div class="r_btn">';
        html += '<a data-type="next" class="abtn orange" href="javascript:;">马上支付</a>';
        html += '</div>';
        html += '</div>';


        return html;
    },
    setup: function (data) {
        this.$inner.html(this.template(data));
    },
    init: function () {
        var _this = this;

        this.$inner = this.$element.find(".c_inner");

        this.$element.on("click", "a", function () {
            var $this = $(this);
            var type = $this.attr("data-type");

            if (type == "next") {
                if (_this.shoppingCartIds.length > 0) {
                    window.location.href = window.ctx + "orderConfirm/orderConfirm.html#shoppingCartIds=" + _this.shoppingCartIds.join("|");
                }
                else {
                    alert("至少选择1门课程");
                }
            }
        });

    }

});

jc.uiExtend("orderConfirmList", {
    template: function (opt) {
        var html = '';

        html += '<div class="o_list">';
        for (var i = 0, l = opt.list.length; i < l; i++) {
            var $cur = $(opt.list[i]);
            html += '<div class="l_item"><div class="i_txt">' + ($cur.find(".r_title").html() || '') + '<span>' + ($cur.find(".r_price").html() || '') + '</span></div></div>';
        }

        var discount = opt.discount;

        html += '</div>';
        html += '<div class="o_discount">';
        html += '<div class="d_item"><div class="i_txt">已优惠：' + discount.discountPrice + '元</div></div>';
        html += '<div class="d_item"><div class="i_txt">优惠规则：' + discount.discount.ruleName + '</div></div>';
        html += '<div class="d_item"><div class="i_txt">共：' + discount.payPrice + '元</div></div>';
        html += '</div>';


        return html;
    },
    setup: function (data) {
        this.$element.html(this.template(data));
    },
    init: function () {
    }
});

jc.uiExtend("orderConfirmFooter", {
    shoppingCartIds: "",
    template: function (opt) {
        var html = '';

        this.shoppingCartIds = opt.shoppingCartIds;

        html += '<div class="i_left">';
        html += '<div class="l_discount">';
        html += '已优惠：￥' + opt.discountPrice;
        html += '</div>';
        html += '<div class="l_price">';
        html += '共需支付：￥' + opt.payPrice;
        html += '</div>';
        html += '</div>';
        html += '<div class="i_right">';
        html += '<div class="r_btn">';
        html += '<a data-type="next" class="abtn orange" href="javascript:;">确定订单</a>';
        html += '</div>';
        html += '</div>';


        return html;
    },
    setup: function (data) {
        this.$inner.html(this.template(data));
    },
    init: function () {
        var _this = this;

        this.$inner = this.$element.find(".o_inner");

        this.$element.on("click", "a", function () {
            var $this = $(this);
            var type = $this.attr("data-type");

            if (type == "next") {

                if (window.orderConfirmNext) window.orderConfirmNext(_this.shoppingCartIds);
            }
        });

    }
});

jc.uiExtend("txtBtnList", {
    template: function (opt) {
        var html = '';

        html += '<div class="t_item">';
        html += '<div class="i_txt">' + opt.title + '</div>';

        if (opt.btnTxt) {
            html += '<div class="i_btn">';
            html += '<a class="' + (opt.btnClass || "") + '" href="' + (opt.btnHref || 'javascript:;') + '">' + opt.btnTxt + '</a>';
            html += '</div>';
        }

        html += '</div>';

        return html;
    },
    setup: function (data) {

        var html = '';

        for (var i = 0, l = data.length; i < l; i++) {
            html += this.template(data[i]);
        }

        this.$list.html(html);
    },
    init: function () {
        this.$list = this.$element.find(".t_list");


    }
});

jc.uiExtend("login", {
    confim: function () {
        var data = {};
        this.$item.not(".hide").each(function (i, obj) {
            var $this = $(obj);
            var $input = $this.find("input");

            if ($input.val()) {
                data[$this.attr("data-id")] = $input.val();
            }
            else {
                data = null;
            }

        });
        return data;
    },
    captchaFacetimeUpdate: function (username) {

        var _this = this;

        $.getJSON(window.path.checkNeedCaptcha, {
            username: username
        }, function (result) {
            if (result.success) {
                var data = result.data;
                if (data.needCaptcha) {
                    _this.captchaShow();
                }
                else {
                    _this.captchaHide();
                }
            }
        });
    },
    captchaShow: function () {
        this.$item_captcha.removeClass("hide");
        this.$item_captcha_img.attr("src", window.path.captcha + "?u=" + (jc.cookie.get("u") || "") + "&t=" + new Date().getTime());
    },
    captchaHide: function () {
        this.$item_captcha.addClass("hide");
    },
    submit: function () {

        var _this = this;

        var submitData = this.confim();

        if (submitData) {
            submitData.u = jc.cookie.get("u");
            if (submitData.captcha) {
                submitData.captchaCode = submitData.captcha
            }
            $.getJSON(window.path.login, submitData, function (result) {

                var data = result.data;

                if (result.success) {
                    var user = data.user;

                    jc.cookie.add("accessToken", data.accessToken);
                    jc.cookie.add("uid", user.uid);
                    jc.cookie.add("avatar", user.avatar);
                    jc.cookie.add("username", user.username);

                    var callbackUrl = jc.hash.get("callbackUrl");

                    if (callbackUrl) {
                        window.location.replace(decodeURIComponent(callbackUrl));
                    }
                    else {
                        window.location.replace(window.ctx + "index/index.html");
                    }
                }
                else {
                    alert(result.desc);
                    if (data && data.failTime >= 3) {
                        _this.captchaShow();
                    }
                }
            });
        }
        else {
            alert("亲！您是不是忘了填点什么?");
        }
    },
    init: function () {
        var _this = this;

        this.$item = this.$element.find(".i_item");
        this.$item_captcha = this.$item.filter("[data-id='captcha']");
        this.$item_captcha_img = this.$item_captcha.find("img");

        this.$item_captcha_img.click(function () {
            _this.captchaShow();
        });

        this.$item.on("blur", "input", function () {
            var id = $(this).parents(".i_item").attr("data-id");
            var value = $(this).val();

            if (id == "username" && value) {
                _this.captchaFacetimeUpdate(value);
            }


        });

    }

});

jc.uiExtend("userDetails", {
    template: function (opt) {
        var html = '';

        if (opt.avatar) {
            opt.avatar = opt.avatar + "?imageMogr/auto-orient";
        }

        html += '<div class="u_header">';
        html += '<div class="h_left">';
        html += '<div class="l_return"><a href="javascript:window.history.go(-1);"><i class="icon">&#xe408;</i></a></div>';
        html += '</div>';
        html += '<div class="h_right">';
        html += '<div class="r_logout">';
        html += '<a href="' + window.ctx + 'index/index.html">首页</a>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
        html += '<div class="u_main">';
        html += '<div class="m_face">';
        html += '<a id="uploadAvatar" href="javascript:;">';
        html += '<img src="' + (opt.avatar || "../images/default_face.png") + '" />';
        html += '</a>';
        html += '</div>';
        html += '<div class="m_details">';
        html += '<div class="d_realName">' + opt.realName + '</div>';
        html += '<div class="d_phoneNo">' + opt.phoneNo + '</div>';
        html += '</div>';
        html += '</div>';

        return html;
    },
    setup: function (data) {
        var _this = this;

        this.$element.html(this.template(data));

        this.$main = this.$element.find(".u_main");
        this.$main_face = this.$main.find(".m_face");
        this.$main_face_a = this.$main_face.find("a");
        this.$main_face_a_img = this.$main_face_a.find("img");
        this.$main_face_a_input = this.$main_face_a.find("input");

        var $input = this.$element.find("input");

        var uploader = Qiniu.uploader({
            runtimes: 'html5,flash,html4',    //上传模式,依次退化
            browse_button: 'uploadAvatar',       //上传选择的点选按钮，**必需**
            uptoken_url: window.path.uploadToken,            //Ajax请求upToken的Url，**强烈建议设置**（服务端提供）
            save_key: true,   // 默认 false。若在服务端生成uptoken的上传策略中指定了 `sava_key`，则开启，SDK会忽略对key的处理
            domain: window.qiniuCDN,   //bucket 域名，下载资源时用到，**必需**
            get_new_uptoken: true,  //设置上传文件的时候是否每次都重新获取新的token
            //container: 'uploadAvatarContainer',           //上传区域DOM ID，默认是browser_button的父元素，
            max_file_size: '100mb',           //最大文件体积限制
            flash_swf_url: window.ctx + 'js/plupload-2.1.9/js/Moxie.swf',  //引入flash,相对路径
            max_retries: 3,                   //上传失败最大重试次数
            dragdrop: false,                   //开启可拖曳上传
            //drop_element: 'uploadAvatarContainer',        //拖曳上传区域元素的ID，拖曳文件或文件夹后可触发上传
            chunk_size: '4mb',                //分块上传时，每片的体积
            auto_start: true,                 //选择文件后自动上传，若关闭需要自己绑定事件触发上传
            filters: {
                max_file_size: '100mb',
                prevent_duplicates: false,
                mime_types: [
                    { title: "Image files", extensions: "jpg,gif,png" }
                ]
            },
            init: {
                'BeforeUpload': function (up, file) {
                    jc.loading.show();
                },
                'FileUploaded': function (up, file, info) {
                    var url = window.qiniuCDN + $.parseJSON(info).url;
                    _this.$main_face_a_input.val(url);
                    _this.$main_face_a_img.attr("src", url);

                    jc.ui.header.trigger("getUser", function (user) {
                        if (user) {
                            $.getJSON(window.path.profileUpdate, {
                                accessToken: user.accessToken,
                                uid: user.uid,
                                avatar: url
                            }, function (result) {
                                jc.loading.hide();
                                if (result.success) {
                                    jc.ui.header.trigger("getUser", function (user) {
                                        if (user) {
                                            jc.cookie.add("avatar", url);
                                        }
                                    });
                                }
                                else {
                                    window.errorRouter(result.desc);
                                }
                            });
                        }

                    }, true);



                },
                'Error': function (up, err, errTip) {
                    //上传出错时,处理相关的事情
                    alert("上传失败:" + errTip)
                }
            }
        });

    },
    init: function () {
        var _this = this;







    }
});

jc.uiExtend("iconList", {
    template: function (opt) {
        var html = '';

        html += '<div class="l_item">';
        html += '<a href="' + (opt.href ? opt.href : "javasript:;") + '">';
        html += '<i>';
        html += '<img src="' + opt.imgUrl + '" />';
        html += '</i>';
        html += '<span>' + opt.title + (opt.count ? '<span class="cDefault">' + opt.count + '</span>' : "") + '</span>';
        html += '</a>';
        html += '</div>';

        return html;
    },
    setup: function (data) {
        var html = '';
        for (var i = 0, l = data.length; i < l; i++) {
            html += this.template(data[i]);
        }
        this.$list.html(html);
    },
    init: function () {
        this.$list = this.$element.find(".i_list");

    }

});

jc.uiExtend("form", {
    getValue: function (id, fn) {
        var value = this.$item.filter("[data-id='" + id + "']").find("input,select").val();
        if (fn) fn(value);

    },
    confim: function (fn) {
        var _this = this;

        var data = {};

        this.$item.each(function (i, obj) {
            var $obj = $(obj);
            var id = $obj.attr("data-id");
            var $control = $obj.find("input,select");

            data[id] = "";
            data[id] = $control.val();

            if (!$control.val()) {
                data = null;
                return false;
            }

        });

        if (fn) {
            fn(data);
        }

    },
    ready: function (data) {
        for (var attr in data) {
            this.$item.filter("[data-id='" + attr + "']").find("input,select").val(data[attr]);
        }

    },
    init: function () {
        this.$item = this.$element.find(".f_item");

        this.$element.on("input", "input", function (e) {

            var e = e || window.event;

            var $this = $(this);
            var type = $this.attr("data-type");
            var value = $this.val();

            if (type == "chinese") {
                $this.val(value.replace(/[^\u4E00-\u9FA5]/g, ''));
            }
        });


        this.$element.on("blur", "input", function () {
            if (window.formInputBlur) window.formInputBlur(this);
        });

        this.$element.on("click", "a", function () {
            if (window.formBtnClick) window.formBtnClick(this);
        });

    }
});

jc.uiExtend("formList", {
    getProvince: function (fn) {

        var result = [];

        for (var i = 0, l = citylist.citylist.length; i < l; i++) {
            var cur = citylist.citylist[i];
            var object = { title: cur.p, value: cur.p };
            result[i] = object;
        }

        if (fn) fn(result);
    },
    getCity: function (province, fn) {

        var result = [];
        if (province == "") {
            result[j] = { title: "请选择", value: "" };
        }
        else {
            for (var i = 0, l = citylist.citylist.length; i < l; i++) {
                var cur = citylist.citylist[i];

                if (province == cur.p) {
                    for (var j = 0, len = cur.c.length; j < len; j++) {
                        result[j] = { title: cur.c[j].n, value: cur.c[j].n };
                    }
                }
            }
        }


        if (fn) fn(result);
    },
    change: function () {

        if (window.formListChange) {

            var $item_id = this.$list_item.filter("[data-id]");

            var data = {};

            $item_id.each(function (i, obj) {
                var $obj = $(obj);
                var id = $obj.attr("data-id");
                var $select = $obj.find("select");
                if ($select.length) {
                    data[id] = $select.val();
                }
            });
            window.formListChange(data);

        }
    },
    template: function (opt) {
        var html = '';

        html += '<div data-id=' + opt.id + ' class="l_item">';
        html += '<span>' + opt.title + '</span>';
        html += '<i></i>';
        html += '<a href="' + (opt.href ? opt.href : "javascript:;") + '">' + opt.value + '</a>';

        if (opt.select) {
            html += '<select>';
            for (var i = 0, l = opt.select.length; i < l; i++) {
                var cur = opt.select[i];
                html += '<option ' + (opt.value == cur.value ? 'selected="selected"' : "") + ' value="' + cur.value + '">' + cur.title + '</option>';
            }
            html += '</select>';
        }

        html += '</div>';

        return html;
    },
    ready: function (opt) {
        for (var i = 0, l = opt.length; i < l; i++) {
            var cur = opt[i];
            this.$list.append(this.template(cur));

        }
        this.$list_item = this.$list.children();
    },
    init: function () {
        var _this = this;
        this.$list = this.$element.find(".f_list");
        this.$list_item = null;

        this.$element.on("change", "select", function () {
            var $this = $(this);
            var $prev = $this.prev();

            var id = $this.parents(".l_item").attr("data-id");

            if ($prev.is("a")) {
                $prev.html($this.children().not(function () { return !this.selected }).html());
            }
            if (id == "location1") {

                var html = '';
                var value = $this.val();

                if (value == "") {
                    html = '<option value="">请选择</option>';
                }
                else {
                    _this.getCity(value, function (array) {
                        for (var i = 0, l = array.length; i < l; i++) {
                            var cur = array[i];
                            html += '<option value="' + cur.title + '">' + cur.value + '</option>';
                        }
                    });
                }

                _this.$list_item.filter("[data-id='location2']").find("select").html(html).trigger("change");
            }



            _this.change();
        });



    }
});

jc.uiExtend("btnGroup", {
    init: function () {
        this.$element.on("click", "a", function () {
            if (window.btnGroupClick) window.btnGroupClick(this);
        });

    }
});

jc.uiExtend("categoryTab", {
    template: function (opt) {
        var html = '';
        html += '<div data-value="' + opt.value + '" class="t_item' + (opt.hasClass ? " current" : "") + '"><a href="javascript:;">' + opt.key + '</a></div>';

        return html;
    },
    setup: function (data) {
        var html = '';
        for (var i = 0, l = data.length; i < l; i++) {
            html += this.template(data[i]);
        }
        this.$title.html(html);

    },
    init: function () {
        this.$title = this.$element.find(".i_title");

        this.$element.on("click", ".i_title .t_item", function () {
            var $this = $(this);
            $this.addClass("current").siblings().removeClass("current");
            if (window.categoryTabChange) window.categoryTabChange($this.attr("data-value"));
        });

    }
});

jc.uiExtend("living", {
    mediaelementMedia: null,
    freeSecond: 0,
    freeTimer: null,
    videoType: "",
    videoUrl: "",
    flashChecker: function () {
        var hasFlash = 0; //是否安装了flash
        var flashVersion = 0; //flash版本
        if (document.all) {
            var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
            if (swf) {
                hasFlash = 1;
                VSwf = swf.GetVariable("$version");
                flashVersion = parseInt(VSwf.split(" ")[1].split(",")[0]);
            }
        } else {
            if (navigator.plugins && navigator.plugins.length > 0) {
                var swf = navigator.plugins["Shockwave Flash"];
                if (swf) {
                    hasFlash = 1;
                    var words = swf.description.split(" ");
                    for (var i = 0; i < words.length; ++i) {
                        if (isNaN(parseInt(words[i]))) continue;
                        flashVersion = parseInt(words[i]);
                    }
                }
            }
        }
        return { f: hasFlash, v: flashVersion };
    },
    setupFree: function (second) {

        var _this = this;

        this.freeSecond = second;

        if (this.freeSecond == 999999) {
            /* 无试听 */

        }
        else if (this.freeSecond <= 0) {
            /* 试听结束 */
            this.freeOver();
        }
        else {
            /* 倒计时 */
            this.freeTimer = setInterval(function () {
                _this.freeSecond--;
                console.log(_this.freeSecond);
                if (_this.freeSecond <= 0) {
                    window.location.reload();

                }
            }, 1000);

        }

    },
    freeOver: function () {
        window.location.href = window.ctx + "player/freeOver.html#lectureId=" + window.lectureId;
    },
    template: function (opt) {
        var html = '';

        html += '<video id="playerVideo" style="width:100%;height:4rem;" preload="none" autoplay="autoplay" class="video-js" controls>'
        html += '</video>'

        return html;
    },
    setup: function (data) {


        if (data.streamStatus == "connected") {
            if (this.flashChecker().f) {
                this.videoType = "video/flv";
                this.videoUrl = data.flvUrl;

            } else {
                this.videoType = "application/x-mpegURL";
                this.videoUrl = data.url;
            }
        } else {
            this.videoType = "application/x-mpegURL";
            this.videoUrl = data.playbackUrl;
        }

        var object = {
            videoType: this.videoType,
            videoUrl: this.videoUrl
        }


        this.$video.html(this.template(object));
        neplayer = neplayer('playerVideo');
        neplayer.setDataSource({src :object.videoUrl ,type : object.videoType })
        neplayer.play()

    },
    init: function () {
        this.$video = this.$element.find(".l_video");

    }

});

jc.uiExtend("video", {
    mediaelementMedia: null,
    freeSecond: 0,
    freeTimer: null,
    videoType: "",
    videoUrl: "",
    flashChecker: function () {
        var hasFlash = 0; //是否安装了flash
        var flashVersion = 0; //flash版本
        if (document.all) {
            var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
            if (swf) {
                hasFlash = 1;
                VSwf = swf.GetVariable("$version");
                flashVersion = parseInt(VSwf.split(" ")[1].split(",")[0]);
            }
        } else {
            if (navigator.plugins && navigator.plugins.length > 0) {
                var swf = navigator.plugins["Shockwave Flash"];
                if (swf) {
                    hasFlash = 1;
                    var words = swf.description.split(" ");
                    for (var i = 0; i < words.length; ++i) {
                        if (isNaN(parseInt(words[i]))) continue;
                        flashVersion = parseInt(words[i]);
                    }
                }
            }
        }
        return { f: hasFlash, v: flashVersion };
    },
    setupFree: function (second) {

        var _this = this;

        this.freeSecond = second;

        if (this.freeSecond == 999999) {
            /* 无试听 */

        }
        else if (this.freeSecond <= 0) {
            /* 试听结束 */
            this.freeOver();
        }
        else {
            /* 倒计时 */
            this.freeTimer = setInterval(function () {
                _this.freeSecond--;
                console.log(_this.freeSecond);
                if (_this.freeSecond <= 0) {
                    clearInterval(_this.freeTimer);
                    window.location.reload();

                }
            }, 1000);

        }

    },
    freeOver: function () {
        window.location.href = window.ctx + "player/freeOver.html#lectureId=" + window.lectureId;
        //jc.ui.freeOver.trigger("show");
    },
    template: function (opt) {
        var html = '';

        html += '<video id="playerVideo" style="width:100%;height:4rem;" preload="none" autoplay="autoplay" class="video-js" controls>'
        html += '<source type="' + opt.videoType + '" src="' + opt.videoUrl + '" /></video>'

        return html;
    },
    setup: function (data) {

        var _this = this;

        var object = {
            videoType: "video/mp4",
            videoUrl: data
        }

        this.$video.html(this.template(object));
        neplayer('playerVideo');

    },
    init: function () {
        this.$video = this.$element.find(".v_video");

    }
});

jc.uiExtend("freeOver", {
    show: function () {
        this.$element.show();
    },
    hide: function () {
        this.$element.hide();
    },
    buy: function (courseId) {

        var _this = this;

        window.location.href = window.ctx + "/courseDetails/courseDetails.html#courseId=" + courseId;

        return false;


        jc.ui.header.trigger("getUser", function (user) {
            if (!user) {
                window.errorRouter("login");
            }
            else {
                $.getJSON(window.path.cartAdd, { accessToken: user.accessToken, userId: user.uid, courseId: courseId }, function (result) {
                    if (result.success) {
                        var data = result.data;
                        window.location.href = window.ctx + "orderConfirm/orderConfirm.html#shoppingCartIds=" + data.shoppingCartId;
                    }
                    else {
                        window.errorRouter(result.desc);
                    }
                });
            }
        });


    },
    template: function (opt) {
        var html = '';

        html += '<div class="f_inner">';
        html += '<div class="i_picture">';
        html += '<img src="' + opt.cover + '" />';
        html += '</div>';
        html += '<div class="i_title">';
        html += '' + opt.title + "，试听结束";
        html += '</div>';
        html += '<div class="i_btn">';
        html += '<a class="abtn green" href="javascript:jc.ui.freeOver.trigger(\'buy\',\'' + opt.courseId + '\');">购买课程</a>';
        html += '</div>';
        html += '</div>';

        return html;
    },
    setup: function (data) {
        this.$element.html(this.template(data));
    },
    init: function () {
    }
});

jc.uiExtend("buyConfim", {
    show: function () {
        this.$element.show();
    },
    init: function () {
        this.$btn_a = this.$element.find(".i_btn a");


        this.$btn_a.click(function () {

            window.location.href = window.ctx + "home/orderList.html";
        });
    }

});